// 定义组合式API仓库
import { defineStore } from 'pinia'
import { getPrefixName } from '@/config'
import type { loginFormInt } from '@/api/system/login/types'
import { loginApi } from '@/api/system/login/index'
import router from '@/router'
interface userInfoStoreInt {
  token: string
  user: {
    id: number;
    createdBy: string;
    createdTime: string;
    updatedBy: string;
    updatedTime: string;
    username: string;
    nickname: string;
    gender: number;
    avatar: string;
    phone: string;
    status: number;
    token: string;

  } // 真实数据接入之后修改为指定类型
}
const ConstantUser = {
  token: '',
    user: {
      id: -1,
      createdBy: '',
      createdTime: '',
      updatedBy: '',
      updatedTime: '',
      username: '',
      nickname: '',
      gender: -1,
      avatar: '',
      phone: '',
      status: -1,
      token: '',
    }
}
// 创建小仓库
export default defineStore(getPrefixName('user'), () => {
  const token = ref('')
  const userInfo = ref<userInfoStoreInt>(ConstantUser)
  // const token = computed(() => {
  //   return userInfo.value.token || ''
  // })
  const user = computed(() => {
    return userInfo.value.user
  })

  // token设置
  function setToken(params: string) {
    token.value = params;
  }

  // 账号登录
  function loginAccount(params: loginFormInt) {
    return new Promise((resolve, reject) => {
      loginApi(params)
        .then((res) => {
          userInfo.value.user = res.data
          setToken(res.data.token)
          // window.localStorage.setItem(getPrefixName('token'), res.data.token)
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }


  // 退出登录
  function logOut() {
    userInfo.value = ConstantUser
    token.value = ''
    // router.replace('/login')
  }
  return {
    token,
    user,
    userInfo,
    logOut,
    setToken,
    loginAccount,
  }
})
